import 'package:flutter/material.dart';
import 'package:flutterclue/mvp/page/ClueDetailPage.dart';
import 'package:flutterclue/utils/ShowSnackBarUtil.dart';
import 'package:flutterclue/utils/ToastUtilForAndroid.dart';
import 'package:flutterclue/view/EndLine.dart';
import 'package:flutterclue/view/progreess_dialog.dart';
import 'package:flutterclue/mvp/mode/ClueListBean.dart';
import 'package:flutterclue/mvp/presenter/ClueListPagePresenter.dart';

class ClueListPage extends StatefulWidget {
  final _tabType;
  final _timeType;

  ClueListPage(this._tabType, this._timeType);

  @override
  State<StatefulWidget> createState() => new _ClueListPageState();
}

class _ClueListPageState extends State<ClueListPage>
    with AutomaticKeepAliveClientMixin
    implements ClueListPageView {
  List<ClueBean> _dataList = new List();

  var _scrollController;
  ClueListPagePresenter _clueListPagePresenter = new ClueListPagePresenter();
  final GlobalKey<RefreshIndicatorState> _refreshIndecatorKey = new GlobalKey();
  bool isFirstLoad = false;
  bool _isShowLoading = false;
  bool _isSliedeUo = false;
  var pageIndex = 1;

  void _scrollListener() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      _isShowLoading = true;
      setState(() {});
      _loadData();
    }
  }

  Future<Null> _loadData() async {
    _isSliedeUo = false;
    pageIndex++;
    await _clueListPagePresenter.getClueListData(
        widget._timeType, pageIndex, widget._tabType);
    setState(() {});
  }

  Future<Null> _refreshData() async {
    _isSliedeUo = true;
    pageIndex = 1;
    await _clueListPagePresenter.getClueListData(
        widget._timeType, pageIndex, widget._tabType);
    setState(() {});
  }

  @override
  dismissLoadingView() {
    isFirstLoad = false;
    setState(() {});
  }

  @override
  void onFail(String s) {
    ToastUtil.showShort(s);
  }

  @override
  void onSuccessData(ClueListBean clueDetailBean) {
    if (!mounted) return;
    if (_isSliedeUo) {
      _dataList.clear();
    } else {
      if (clueDetailBean.ClueList.isEmpty) {
        _isShowLoading = false;
      } else {
        _isShowLoading = true;
      }
    }
    _dataList.addAll(clueDetailBean.ClueList);
    setState(() {});
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _clueListPagePresenter.attachView(this);
    _scrollController = new ScrollController()..addListener(_scrollListener);
    isFirstLoad = true;
    _refreshData();
  }

  @override
  void didUpdateWidget(ClueListPage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    _refreshData();
  }

  @override
  Widget build(BuildContext context) {
    var content;
    if (isFirstLoad) {
      content = getProgressDialog();
    } else if (_dataList.isEmpty) {
      content = Material(
        color: Colors.white,
        child: InkWell(
          onTap: (){
            _refreshData();
          },
          child: new Container(
              child: Center(
                child: new Text('暂无数据,触摸刷新'),
              )),
        ),
      );
    } else {
      content = ListView.builder(
          itemCount: _dataList.length + 1,
          controller: _scrollController,
          physics: AlwaysScrollableScrollPhysics(),
          itemBuilder: buildItem);
    }
    var _refreshIndecator = new RefreshIndicator(
      child: content,
      onRefresh: _refreshData,
      key: _refreshIndecatorKey,
    );
    return _refreshIndecator;
  }

  Widget buildItem(BuildContext context, int index) {
    if (index == _dataList.length) {
      if (_isShowLoading) {
        return new LoadMoreView();
      } else {
        return new EndLine();
      }
    } else {
      return Container(
        color: Color(0xfff4f4f4),
        child: Column(
          children: <Widget>[
            new Material(
              color: Colors.white,
              child: InkWell(
                onTap: () {
                  Navigator.of(context).push(new PageRouteBuilder(
                      opaque: false,
                      pageBuilder: (BuildContext context, _, __) {
                        return new ClueDetailPage(
                            clueId: _dataList[index].ClueId);
                      },
                      transitionsBuilder:
                          (_, Animation<double> animation, __, Widget child) {
                        return new SlideTransition(
                          //相当于android中的估值器
                          position: new Tween<Offset>(
                            begin: const Offset(1.0, 0.0),
                            end: const Offset(0.0, 0.0),
                            //相当于android中的差值器
                          ).animate(new CurvedAnimation(
                              parent: animation, curve: Curves.easeOut)),
                          child: child,
                        );
                      }));
                },
                child: new Container(
                  padding: new EdgeInsets.only(left: 16, right: 16, top: 16),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      new Row(
                        children: <Widget>[
                          Icon(Icons.card_giftcard,
                              size: 12, color: Color(0xff999999)),
                          Expanded(
                              child: new Padding(
                            padding: EdgeInsets.only(left: 5),
                            child: new Text("保险公司线索",
                                style: TextStyle(
                                    color: Color(0xff999999), fontSize: 12)),
                          )),
                          Text(
                              _getDateFormat(_dataList[index].UpdateTime,
                                  _dataList[index].TimeDifference),
                              style: TextStyle(
                                  color: Color(0xff999999), fontSize: 12))
                        ],
                      ),
                      new Padding(padding: EdgeInsets.only(top: 10)),
                      new Row(
                        children: <Widget>[
                          Text(_dataList[index].LicenseNo,
                              style: TextStyle(
                                  color: Color(0xff333333),
                                  fontSize: 18,
                                  fontWeight: FontWeight.bold)),
                          Padding(
                            padding: EdgeInsets.only(left: 4),
                            child: Text(
                                "（超时${_dataList[index].TimeoutNoticeCount}次）",
                                style: TextStyle(
                                    color: Color(0xffFF4444), fontSize: 14)),
                          )
                        ],
                      ),
                      new Padding(padding: EdgeInsets.only(top: 10)),
                      new Container(
                        padding: EdgeInsets.all(6),
                        color: Color(0xffF2F4F5),
                        child: new Text(_dataList[index].SmsContent,
                            style: TextStyle(
                                color: Color(0xff666666), fontSize: 14)),
                      ),
                      new Offstage(
                        offstage: false,
                        child: new Column(
                          children: <Widget>[
                            new Padding(padding: EdgeInsets.only(top: 8)),
                            new Row(
                              children: <Widget>[
                                Text("手机号",
                                    style: TextStyle(
                                        color: Color(0xff999999),
                                        fontSize: 14)),
                                Padding(
                                  padding: EdgeInsets.only(left: 20),
                                  child: Text(_dataList[index].Mobile,
                                      style: TextStyle(
                                          color: Color(0xff666666),
                                          fontSize: 14)),
                                )
                              ],
                            ),
                          ],
                        ),
                      ),
                      new Padding(padding: EdgeInsets.only(top: 8)),
                      new Row(
                        children: <Widget>[
                          Text("报案人",
                              style: TextStyle(
                                  color: Color(0xff999999), fontSize: 14)),
                          Padding(
                            padding: EdgeInsets.only(left: 20),
                            child: Text(_dataList[index].ReportCasePeople,
                                style: TextStyle(
                                    color: Color(0xff666666), fontSize: 14)),
                          )
                        ],
                      ),
                      new Padding(padding: EdgeInsets.only(top: 8)),
                      new Container(
                        child: new Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text("承保险种",
                                style: TextStyle(
                                    color: Color(0xff999999), fontSize: 14)),
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.only(left: 4, bottom: 16),
                                child: Text(_dataList[index].InsureInfo,
                                    textDirection: TextDirection.ltr,
                                    style: TextStyle(
                                        color: Color(0xff666666),
                                        fontSize: 14)),
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            new Padding(padding: EdgeInsets.only(top: 10))
          ],
        ),
      );
      ;
    }
  }

  String _getDateFormat(String createTime, double timeDifference) {
    if (timeDifference == null) {
      return createTime;
    }
    double mMessageTime = timeDifference / 60 + 0.5;
    if (mMessageTime < 60) {
      if (mMessageTime == 0) {
        return "现在";
      } else {
        return "${mMessageTime}分钟前";
      }
    } else if (mMessageTime < 1439 && mMessageTime >= 60) {
      return "${(mMessageTime / 60.0 + 0.5).toInt()}小时前";
    } else {
      return createTime.substring(0, 10);
    }
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _scrollController.removeListener(_scrollListener);
  }

  @override
  showLoadingView() {}
}
